package com.cloud.yangfeiself.filter;


import com.cloud.yangfeiself.dto.ResResult;
import com.cloud.yangfeiself.util.JwtUtil;
import com.cloud.yangfeiself.util.WebUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
public class JwtFilter implements Filter {

    private static final String EXPIRED_JWT_EXCEPTION_MSG = "token已过期";
    private static final String SIGNATURE_EXCEPTION__MSG = "token验签失败";
    private static final String JWT_EXCEPTION_MSG = "token错误";
    private static final String EXCEPTION_MSG = "服务器繁忙";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = ((HttpServletRequest) request).getHeader("Authorization");
        if (StringUtils.isEmpty(token) || token.indexOf("bearer ") == -1) {
            WebUtil.responseJson(ResResult.error(HttpStatus.UNAUTHORIZED.value(), "token is need"));
            return;
        } else {
            String jwtToken = token.substring(7);

            try {
                jwtUtil.checkToken(jwtToken);
            } catch (ExpiredJwtException e) {
                WebUtil.responseJson(ResResult.error(HttpStatus.UNAUTHORIZED.value(), EXPIRED_JWT_EXCEPTION_MSG));
                return;
            } catch (SignatureException e) {
                WebUtil.responseJson(ResResult.error(HttpStatus.UNAUTHORIZED.value(), SIGNATURE_EXCEPTION__MSG));
                return;
            } catch (JwtException e) {
                WebUtil.responseJson(ResResult.error(HttpStatus.UNAUTHORIZED.value(), JWT_EXCEPTION_MSG));
                return;
            } catch (Exception e) {
                log.error("token 验证未知异常");
                WebUtil.responseJson(ResResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), EXCEPTION_MSG));
                return;
            }
//            抓取异常处理后续继续会继续执行，响应异常信息后需return(业务逻辑不应该执行)
            System.out.println("jwtToken 错误执行。。。。。。。 = " + jwtToken);
            chain.doFilter(request, response);
        }
    }

    public static void main(String[] args) {
        System.out.println("\"bearer XXX\".substring(bearer) = " + "bearer XXX".indexOf("bearer "));
    }

    private JwtUtil jwtUtil;

    public JwtFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }
}
